package cn.school.demo.ui.forget_password

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.school.demo.R
import cn.school.demo.databinding.FragmentForgetPasswordFirstBinding
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils

class ForgetPasswordFirstFragment : Fragment() {
    private lateinit var viewModel: ForgetPasswordViewModel
    private var _binding: FragmentForgetPasswordFirstBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(ForgetPasswordViewModel::class.java)
        _binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_forget_password_first,
            container,
            false
        )
        binding.vm = viewModel
        binding.view = this
        binding.lifecycleOwner = viewLifecycleOwner
        return binding.root
    }

    fun forgetPasswordIdentityButton() {
        val toastText = viewModel.dataDetection()
        toastText?.let { ToastUtils.showShort(toastText) } ?: let {
            viewModel.getResult()
            viewModel.result.observe(viewLifecycleOwner) {
                LogUtils.d("我回调了！！")
                when (viewModel.result.value?.success) {
                    true -> {
                        val paramMap =
                            mapOf("id" to viewModel.id.value, "phone" to viewModel.phone.value)
                        val bundle: Bundle = bundleOf(Pair("map", GsonUtils.toJson(paramMap)))
                        LogUtils.d(bundle)
                        findNavController().navigate(R.id.action_forget_pwd_first_to_forget_pwd_second,bundle)
                    }
                    else -> {
                        LogUtils.e(viewModel.result.value?.message)
                        ToastUtils.showLong(viewModel.result.value?.message)
                    }
                }

            }
        }
    }

    fun setId() = viewModel.setId(binding.forgetPasswordIDEditView.text.toString())
    fun setPhone() = viewModel.setPhone(binding.forgetPasswordPhoneEditView.text.toString())
}